/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.tonyodev.fetch2rx.rxohos;

import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

import java.util.concurrent.Callable;

import io.reactivex.Scheduler;

/**
 * OhosSchedulers
 *
 * @since 2021-05-21
 */
public class OhosSchedulers {
    /**
     * MainHolder
     *
     * @since 2021-05-21
     */
    private static final class MainHolder {
        static final Scheduler DEFAULT
            = new HandlerScheduler(new EventHandler(EventRunner.getMainEventRunner()), false);
    }

    private static final Scheduler MAIN_THREAD = RxOhosPlugins.initMainThreadScheduler(
        new Callable<Scheduler>() {
            @Override
            public Scheduler call() throws Exception {
                return MainHolder.DEFAULT;
            }
        });

    private OhosSchedulers() {
        throw new AssertionError("No instances.");
    }

    /**
     * A {@link Scheduler} which executes actions on the Android main thread.
     *
     * @return Scheduler实例
     */
    public static Scheduler mainThread() {
        return RxOhosPlugins.onMainThreadScheduler(MAIN_THREAD);
    }

    /**
     * A {@link Scheduler} which executes actions on {@code looper}.
     *
     * @param looper looper实例
     * @return Scheduler实例
     */
    public static Scheduler from(EventRunner looper) {
        return from(looper, false);
    }

    /**
     * A {@link Scheduler} which executes actions on {@code looper}.
     *
     * @param looper looper实例
     * @param async if true, the scheduler will use async messaging on API >= 16 to avoid VSYNC locking.
     * On API < 16 this value is ignored.
     * @return Scheduler实例
     * @throws NullPointerException 空指针异常
     */
    public static Scheduler from(EventRunner looper, boolean async) {
        if (looper == null) {
            throw new NullPointerException("looper == null");
        }

        return new HandlerScheduler(new EventHandler(looper), async);
    }
}
